package com.mybatisplus.mp.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 中文空白问题：itext缺少相应字体
 */
@RestController
@Slf4j
public class CreatePdfByte {


    /**
     * 生成pdf的字节数组
     */
    @RequestMapping(value = "/generatePDF")
    public byte[] generatePDF(HttpServletResponse response) throws IOException, DocumentException {
        // 不同字体（这里定义为同一种字体：包含不同字号、不同style）
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font titlefont = new Font(bfChinese, 16, Font.BOLD);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//构建字节输出流
        Document doc = null;
        try {
            doc = new Document(new Rectangle(PageSize.A4));// 可配其余4个参数，如（rectPageSize，60,60,60,60）页面边距
            PdfWriter.getInstance(doc, baos);//将PDF文档对象写入到流
            doc.open();
            doc.add(new Paragraph("Hello World 啦啦啦 success!",titlefont));
            if (doc != null) {
                doc.close();
            }
        } catch (Exception e) {
            log.error("PDF异常", e);
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    log.error("PDF异常", e);
                }
            }
        }
        byte[] b = baos.toByteArray();//pdf字节数组
        System.out.println("baos.toByteArray().length:" + baos.toByteArray().length);
        FileCopyUtils.copy(b, response.getOutputStream());
        return b;
    }

    /**
     * 将字节数组转成pdf文件
     *
     * @throws IOException
     */
    @RequestMapping(value = "/array2pdf")
    public void array2pdf(HttpServletResponse response) throws IOException, DocumentException {
        System.out.println("开始生成pdf字节数组");

        byte[] b = generatePDF(response);

        String filename = "D:/array2pdf.pdf";
        FileOutputStream fout = new FileOutputStream(filename);
        //将字节写入文件
        fout.write(b);
        fout.close();
    }
}
